﻿#include "ResultViewer.h"
#include <QBoxLayout>
#include "ImageItem.h"

ResultViewer::ResultViewer(QWidget *parent)
    : QWidget{parent}
{
    setupUi();
}

void ResultViewer::setupUi()
{
    lstwgt = new QListWidget();
    mView = new GraphicsView();

    QHBoxLayout* hLayout = new QHBoxLayout();
    this->setLayout(hLayout);
    hLayout->addWidget(mView);
    hLayout->addWidget(lstwgt);
    hLayout->setStretch(0, 4);
    hLayout->setStretch(1, 1);

    // 连接信号和槽
    connect(lstwgt, &QListWidget::itemClicked, this, &ResultViewer::displayZoomedRegion);
}

void ResultViewer::displayZoomedRegion(QListWidgetItem *item) {
    QRect region = item->data(Qt::UserRole).toRect(); // 获取存储的矩形区域

    if (!mView->itemImg) return; // 确保 pixmapItem 已存在

    // 将图像区域映射到场景坐标
    QRectF sceneRegion = mView->itemImg->mapRectToScene(region);

    // 调整视图，使其正确缩放并居中显示该区域
    mView->fitInView(sceneRegion, Qt::KeepAspectRatio);
}

void ResultViewer::addItem(const QImage& img, QRectF rect)
{
    QListWidgetItem *item = new QListWidgetItem();
    item->setIcon(QIcon(QPixmap::fromImage(img).scaled(lstwgt->width(), lstwgt->width(), Qt::KeepAspectRatio, Qt::SmoothTransformation))); // 设定缩略图
    item->setData(Qt::UserRole, rect); // 存储区域信息
    lstwgt->addItem(item);
}

